package client.comm.baoding.adapter

import android.content.Context
import android.content.Intent
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ObservableField
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import client.comm.baoding.R
import client.comm.baoding.adapter.main.HomeCateGoodAdapter
import client.comm.baoding.api.bean.GoodsIndex
import client.comm.baoding.api.bean.HomeCateRet
import client.comm.baoding.databinding.PagingitemSyheaderBinding
import client.comm.baoding.ui.MainActivity
import client.comm.baoding.ui.SearchActivity
import client.comm.commlib.base.PagingViewHoder
import client.comm.commlib.base.SyBannerAdapter
import client.comm.commlib.comm_ui.draw.SpaceGridItemDecoration
import client.comm.commlib.dipToPx
import client.comm.commlib.getScreenWidth
import client.comm.commlib.utils.Util
import com.bumptech.glide.RequestManager
import com.bumptech.glide.request.RequestOptions
import com.youth.banner.indicator.CircleIndicator

class SyPagingHeaderAdapter(val manager: RequestManager, val context: Context) :
    LoadStateAdapter<PagingViewHoder>() {

    var goodsIndex: GoodsIndex? = null
    lateinit var binding: PagingitemSyheaderBinding
    var he: Float = 0.0f
    val jyCateAdapter: HomeCateGoodAdapter by lazy {
        HomeCateGoodAdapter(context, manager).apply {
            cateCli = this@SyPagingHeaderAdapter.cateCli
        }
    }
    val city = ObservableField<String>("全国")

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): PagingViewHoder {
        return PagingViewHoder(
            DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                R.layout.pagingitem_syheader,
                parent,
                false
            )
        ).apply {
            val itemBinding = this.binding as PagingitemSyheaderBinding
            itemBinding.event = this@SyPagingHeaderAdapter
            this@SyPagingHeaderAdapter.binding = itemBinding
            val h = Util.getStatusBarHeight(context)
            val p = itemBinding.statusBar.layoutParams
            p.height = h
            itemBinding.statusBar.layoutParams = p

            itemBinding.recyclerViewCate.layoutManager = GridLayoutManager(context, 5)
            itemBinding.recyclerViewCate.addItemDecoration(
                SpaceGridItemDecoration(
                    TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 0.1f, context.resources.displayMetrics
                    ).toInt()
                )
            )
            itemBinding.recyclerViewCate.adapter = jyCateAdapter

            val width = getScreenWidth(context) - dipToPx(context.resources, 20.0f)

            val params: ViewGroup.LayoutParams = itemBinding.banner.getLayoutParams()
            params.height = (width * 157 / 420f).toInt()

            itemBinding.banner.layoutParams = params
            itemBinding.banner.indicator = CircleIndicator(context)
            val paramsBg: ViewGroup.LayoutParams = itemBinding.bg.layoutParams
            paramsBg.height = (width * 157 / 420f - dipToPx(context.resources, 5.0f)).toInt()
            itemBinding.bg.layoutParams = paramsBg

            this@SyPagingHeaderAdapter.binding.tabOne.isSelected = true

        }
    }

    override fun onBindViewHolder(holder: PagingViewHoder, loadState: LoadState) {
        goodsIndex?.let {
            binding.event = this

            goodsIndex!!.category_list?.let {
                jyCateAdapter.submitList(it)
            }

            val list = it.banner_list
            binding.banner.setAdapter(object : SyBannerAdapter<GoodsIndex.Banner>(list) {
                override fun onBindView(
                    holder: BannerViewHolder?,
                    data: GoodsIndex.Banner?,
                    position: Int,
                    size: Int
                ) {
                    manager.load(data?.image_url)
                        .apply(RequestOptions().error(R.mipmap.ic_launcher))
                        .into(holder!!.imageView)
                }
            })
            binding.banner.start()


            if (it.category_list_index.size > 0) {
                binding.oneName.text = it.category_list_index[0].name
                binding.oneInfo.text = it.category_list_index[0].name_info
            }
            if (it.category_list_index.size > 1) {
                binding.twoName.text = it.category_list_index[1].name
                binding.twoInfo.text = it.category_list_index[1].name_info

            }
            if (it.category_list_index.size > 2) {
                binding.threeName.text = it.category_list_index[2].name
                binding.threeInfo.text = it.category_list_index[2].name_info
            }
            if (it.category_list_index.size > 3) {
                binding.fourName.text = it.category_list_index[3].name
                binding.fourInfo.text = it.category_list_index[3].name_info
            }

            notifyTab((context as MainActivity).viewModel.homeTabIndex.value!!)

            if (he == 0.0f)
                binding.topWrap.postDelayed({
                    he = binding.topWrap.top.toFloat()
                }, 200)
        }


    }

    var notice: ((ArrayList<GoodsIndex.Article>) -> Unit)? = null
    var cateCli: ((HomeCateRet.Category) -> Unit)? = null

    var tabCli: ((Int) -> Unit)? = null
    var locationCli: (() -> Unit)? = null
    var runMsg: (() -> Unit)? = null
    fun tabClick(i: Int) {
        tabCli?.invoke(i)
    }

    fun locationClick() {
        locationCli?.invoke()
    }

    fun goNotice() {
        notice?.invoke(goodsIndex!!.article_list)
    }

    override fun onViewAttachedToWindow(holder: PagingViewHoder) {
        super.onViewAttachedToWindow(holder)
        val lp: ViewGroup.LayoutParams = holder.itemView.getLayoutParams()
        if (lp != null && lp is StaggeredGridLayoutManager.LayoutParams
        ) {
            lp.isFullSpan = true
        }
    }

    // true显示无论什么状态都显示
    override fun displayLoadStateAsItem(loadState: LoadState): Boolean {
        return super.displayLoadStateAsItem(loadState) || (loadState.endOfPaginationReached)
    }

    fun goSearch() {
        context.startActivity(Intent(context, SearchActivity::class.java))
    }

    fun showMsg() {
        runMsg?.invoke()
    }

    fun setCity(city: String) {
        this.city.set(city)
    }

    fun notifyTab(i: Int) {
        if (::binding.isInitialized)
            when (i) {

                0 -> {
                    binding.tabOne.isSelected = true
                    binding.tabTwo.isSelected = false
                    binding.tabThree.isSelected = false
                    binding.tabFour.isSelected = false
                }

                1 -> {
                    binding.tabOne.isSelected = false
                    binding.tabTwo.isSelected = true
                    binding.tabThree.isSelected = false
                    binding.tabFour.isSelected = false

                }

                2 -> {
                    binding.tabOne.isSelected = false
                    binding.tabTwo.isSelected = false
                    binding.tabThree.isSelected = true
                    binding.tabFour.isSelected = false

                }

                3 -> {
                    binding.tabOne.isSelected = false
                    binding.tabTwo.isSelected = false
                    binding.tabThree.isSelected = false
                    binding.tabFour.isSelected = true

                }
            }
    }
}